/*-------------------------------------------------------------------------
 *
 * heapam.h
 *	  POSTGRES 堆访问方法的定义
 *
 *
 * Portions Copyright (c) 1996-2022, PostgreSQL Global Development Group
 * Portions Copyright (c) 1994, Regents of the University of California
 *
 * src/include/access/heapam.h
 *
 *-------------------------------------------------------------------------
 */
#ifndef HEAPAM_H
#define HEAPAM_H

#include "access/relation.h"	/* 为了向后兼容 */
#include "access/relscan.h"
#include "access/sdir.h"
#include "access/skey.h"
#include "access/table.h"		/* 为了向后兼容 */
#include "access/tableam.h"
#include "nodes/lockoptions.h"
#include "nodes/primnodes.h"
#include "storage/bufpage.h"
#include "storage/dsm.h"
#include "storage/lockdefs.h"
#include "storage/shm_toc.h"
#include "utils/relcache.h"
#include "utils/snapshot.h"


/* heap_insert 的 "options" 标志位 */
#define HEAP_INSERT_SKIP_FSM	TABLE_INSERT_SKIP_FSM
#define HEAP_INSERT_FROZEN		TABLE_INSERT_FROZEN
#define HEAP_INSERT_NO_LOGICAL	TABLE_INSERT_NO_LOGICAL
#define HEAP_INSERT_SPECULATIVE 0x0010

typedef struct BulkInsertStateData *BulkInsertState;
struct TupleTableSlot;

#define MaxLockTupleMode	LockTupleExclusive

/*
 * heap 表扫描的描述符。
 */
typedef struct HeapScanDescData
{
	TableScanDescData rs_base;	/* 描述符的 AM 独立部分 */

	/* 在 initscan 时设置的状态 */
	BlockNumber rs_nblocks;		/* rel 中的块总数 */
	BlockNumber rs_startblock;	/* 开始的块 # */
	BlockNumber rs_numblocks;	/* 要扫描的最大块数 */
	/* rs_numblocks 通常是 InvalidBlockNumber，意味着“扫描整个 rel” */

	/* 扫描当前状态 */
	bool		rs_inited;		/* false = 扫描尚未初始化 */
	BlockNumber rs_cblock;		/* 扫描中的当前块 #（如果有） */
	Buffer		rs_cbuf;		/* 扫描中的当前缓冲区（如果有） */
	/* 注意：如果 rs_cbuf 不是 InvalidBuffer，我们在该缓冲区上保持一个锁定 */

	/* rs_numblocks 通常是 InvalidBlockNumber，意味着“扫描整个 rel” */
	BufferAccessStrategy rs_strategy;	/* 读取的访问策略 */

	HeapTupleData rs_ctup;		/* 扫描中的当前元组（如果有） */

	/*
	 * 用于并行扫描以存储页面分配数据。在未执行并行扫描时为 NULL。
	 */
	ParallelBlockTableScanWorkerData *rs_parallelworkerdata;

	/* 这些字段仅在逐页模式和位图扫描中使用 */
	int			rs_cindex;		/* 当前元组在 vistuples 中的索引 */
	int			rs_ntuples;		/* 页面上可见元组的数量 */
	OffsetNumber rs_vistuples[MaxHeapTuplesPerPage];	/* 他们的偏移量 */
}			HeapScanDescData;
typedef struct HeapScanDescData *HeapScanDesc;

/*
 * 通过索引从堆中获取的描述符。
 */
typedef struct IndexFetchHeapData
{
	IndexFetchTableData xs_base;	/* 描述符的 AM 独立部分 */

	Buffer		xs_cbuf;		/* 扫描中的当前堆缓冲区，如果有的话 */
	/* 注意：如果 xs_cbuf 不是 InvalidBuffer，我们会保持对该缓冲区的锁定 */
} IndexFetchHeapData;

/* HeapTupleSatisfiesVacuum 的结果代码 */
typedef enum
{
	HEAPTUPLE_DEAD,				/* 元组已死亡且可删除 */
	HEAPTUPLE_LIVE,				/* 元组是活的（已提交，无删除者） */
	HEAPTUPLE_RECENTLY_DEAD,	/* 元组已死亡，但尚不可删除 */
	HEAPTUPLE_INSERT_IN_PROGRESS,	/* 插入xact仍在进行中 */
	HEAPTUPLE_DELETE_IN_PROGRESS	/* 删除xact仍在进行中 */
} HTSV_Result;

/* ----------------
 *		堆访问方法的函数原型
 *
 * heap_create、heap_create_with_catalog和heap_drop_with_catalog
 * 在catalog/heap.h中声明
 * ----------------
 */


/*
 * HeapScanIsValid
 *		当且仅当堆扫描有效时为真。
 */
#define HeapScanIsValid(scan) PointerIsValid(scan)

extern TableScanDesc heap_beginscan(Relation relation, Snapshot snapshot,
									int nkeys, ScanKey key,
									ParallelTableScanDesc parallel_scan,
									uint32 flags);
extern void heap_setscanlimits(TableScanDesc scan, BlockNumber startBlk,
							   BlockNumber numBlks);
extern void heapgetpage(TableScanDesc scan, BlockNumber page);
extern void heap_rescan(TableScanDesc scan, ScanKey key, bool set_params,
						bool allow_strat, bool allow_sync, bool allow_pagemode);
extern void heap_endscan(TableScanDesc scan);
extern HeapTuple heap_getnext(TableScanDesc scan, ScanDirection direction);
extern bool heap_getnextslot(TableScanDesc sscan,
							 ScanDirection direction, struct TupleTableSlot *slot);
extern void heap_set_tidrange(TableScanDesc sscan, ItemPointer mintid,
							  ItemPointer maxtid);
extern bool heap_getnextslot_tidrange(TableScanDesc sscan,
									  ScanDirection direction,
									  TupleTableSlot *slot);
extern bool heap_fetch(Relation relation, Snapshot snapshot,
					   HeapTuple tuple, Buffer *userbuf, bool keep_buf);
extern bool heap_hot_search_buffer(ItemPointer tid, Relation relation,
								   Buffer buffer, Snapshot snapshot, HeapTuple heapTuple,
								   bool *all_dead, bool first_call);

extern void heap_get_latest_tid(TableScanDesc scan, ItemPointer tid);

extern BulkInsertState GetBulkInsertState(void);
extern void FreeBulkInsertState(BulkInsertState);
extern void ReleaseBulkInsertStatePin(BulkInsertState bistate);

extern void heap_insert(Relation relation, HeapTuple tup, CommandId cid,
						int options, BulkInsertState bistate);
extern void heap_multi_insert(Relation relation, struct TupleTableSlot **slots,
							  int ntuples, CommandId cid, int options,
							  BulkInsertState bistate);
extern TM_Result heap_delete(Relation relation, ItemPointer tid,
							 CommandId cid, Snapshot crosscheck, bool wait,
							 struct TM_FailureData *tmfd, bool changingPart);
extern void heap_finish_speculative(Relation relation, ItemPointer tid);
extern void heap_abort_speculative(Relation relation, ItemPointer tid);
extern TM_Result heap_update(Relation relation, ItemPointer otid,
							 HeapTuple newtup,
							 CommandId cid, Snapshot crosscheck, bool wait,
							 struct TM_FailureData *tmfd, LockTupleMode *lockmode);
extern TM_Result heap_lock_tuple(Relation relation, HeapTuple tuple,
								 CommandId cid, LockTupleMode mode, LockWaitPolicy wait_policy,
								 bool follow_update,
								 Buffer *buffer, struct TM_FailureData *tmfd);

extern bool heap_inplace_lock(Relation relation,
							  HeapTuple oldtup_ptr, Buffer buffer,
							  void (*release_callback) (void *), void *arg);
extern void heap_inplace_update_and_unlock(Relation relation,
										   HeapTuple oldtup, HeapTuple tuple,
										   Buffer buffer);
extern void heap_inplace_unlock(Relation relation,
								HeapTuple oldtup, Buffer buffer);
extern void heap_inplace_update(Relation relation, HeapTuple tuple);
extern bool heap_freeze_tuple(HeapTupleHeader tuple,
							  TransactionId relfrozenxid, TransactionId relminmxid,
							  TransactionId cutoff_xid, TransactionId cutoff_multi);
extern bool heap_tuple_would_freeze(HeapTupleHeader tuple, TransactionId cutoff_xid,
									MultiXactId cutoff_multi,
									TransactionId *relfrozenxid_out,
									MultiXactId *relminmxid_out);
extern bool heap_tuple_needs_eventual_freeze(HeapTupleHeader tuple);

extern void simple_heap_insert(Relation relation, HeapTuple tup);
extern void simple_heap_delete(Relation relation, ItemPointer tid);
extern void simple_heap_update(Relation relation, ItemPointer otid,
							   HeapTuple tup);

extern TransactionId heap_index_delete_tuples(Relation rel,
											  TM_IndexDeleteOp *delstate);

/* 在heap/pruneheap.c中 */
struct GlobalVisState;
extern void heap_page_prune_opt(Relation relation, Buffer buffer);
extern int	heap_page_prune(Relation relation, Buffer buffer,
							TransactionId oldest_xmin,
							struct GlobalVisState *vistest,
							TransactionId old_snap_xmin,
							TimestampTz old_snap_ts_ts,
							int *nnewlpdead,
							OffsetNumber *off_loc);
extern void heap_page_prune_execute(Buffer buffer,
									OffsetNumber *redirected, int nredirected,
									OffsetNumber *nowdead, int ndead,
									OffsetNumber *nowunused, int nunused);
extern void heap_get_root_tuples(Page page, OffsetNumber *root_offsets);

/* 在 heap/vacuumlazy.c 中 */
struct VacuumParams;
extern void heap_vacuum_rel(Relation rel,
							struct VacuumParams *params, BufferAccessStrategy bstrategy);

/* 在 heap/heapam_visibility.c 中 */
extern bool HeapTupleSatisfiesVisibility(HeapTuple stup, Snapshot snapshot,
										 Buffer buffer);
extern TM_Result HeapTupleSatisfiesUpdate(HeapTuple stup, CommandId curcid,
										  Buffer buffer);
extern HTSV_Result HeapTupleSatisfiesVacuum(HeapTuple stup, TransactionId OldestXmin,
											Buffer buffer);
extern HTSV_Result HeapTupleSatisfiesVacuumHorizon(HeapTuple stup, Buffer buffer,
												   TransactionId *dead_after);
extern void HeapTupleSetHintBits(HeapTupleHeader tuple, Buffer buffer,
								 uint16 infomask, TransactionId xid);
extern bool HeapTupleHeaderIsOnlyLocked(HeapTupleHeader tuple);
extern bool XidInMVCCSnapshot(TransactionId xid, Snapshot snapshot);
extern bool HeapTupleIsSurelyDead(HeapTuple htup,
								  struct GlobalVisState *vistest);

/*
 * 为了避免泄露过多关于 reorderbuffer 实现细节的信息
 * 该功能在 reorderbuffer.c 中实现，而不是在 heapam_visibility.c 中
 */
struct HTAB;
extern bool ResolveCminCmaxDuringDecoding(struct HTAB *tuplecid_data,
										  Snapshot snapshot,
										  HeapTuple htup,
										  Buffer buffer,
										  CommandId *cmin, CommandId *cmax);
extern void HeapCheckForSerializableConflictOut(bool valid, Relation relation, HeapTuple tuple,
												Buffer buffer, Snapshot snapshot);

#endif							/* HEAPAM_H */
